package com.smedi.ismedi.authority.starter.aspect;

import com.smedi.ismedi.authority.starter.annotation.UserActionLog;
import com.smedi.ismedi.authority.starter.common.ResponseData;
import com.smedi.ismedi.authority.starter.feign.InmailFeignClient;
import com.smedi.ismedi.authority.starter.request.UserActionLogRequest;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @className: UserActionLogAspect
 * @Description: TODO
 * @version: v1.0.0
 * @author: wzx
 * @date: 2022/9/29 16:05
 */

@Aspect
@Component
@Slf4j
@Lazy(value = false)
@Order(value = 1)
public class UserActionLogAspect {

    @Resource
    private AuthorityUtil authorityUtil;

    @Resource
    private InmailFeignClient client;

    @Pointcut("@annotation(userActionLog)")
    private void UserActionLogAop(UserActionLog userActionLog){}


    @Before(value = "UserActionLogAop(userActionLog)")
    public void doBefore(JoinPoint joinPoint,UserActionLog userActionLog) {
        try {
            //获取当前操作人ID
            Long userId = authorityUtil.getPersonId();
            //获取访问路径
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert requestAttributes != null;
            HttpServletRequest request = requestAttributes.getRequest();
            String url = request.getRequestURI();
            //访问参数
            Object[] args = joinPoint.getArgs();
            //获取方法具体描述
            String description = userActionLog.description();
            //当前时间
            LocalDateTime localDateTime = LocalDateTime.now();
            UserActionLogRequest entity =new UserActionLogRequest();
            entity.setDescription(description);
            entity.setArgs(Arrays.toString(args));
            entity.setActionTime(localDateTime);
            entity.setVisitUrl(url);
            entity.setUserId(userId);
            ResponseData<Boolean> isSave = client.saveUserAction(entity);
            if(isSave==null || !isSave.getData()){
                log.error("记录用户操作记录{}失败",entity);
            }
        }catch (Exception e){
            log.error("记录用户操作失败，失败原因{}",e.getMessage());
        }

    }

}